using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using GameFrameWork;
using GeneratorConfig = ScriptGenerator.Config;

[CustomEditor(typeof(ScriptHelper), true)]
class ScriptHelperInspector : Editor
{
    SerializedProperty _script;
    SerializedProperty _scriptName;

    string _folder;
    string _mainPath;
    string _variablePath;

    protected virtual void OnEnable()
    {
        _script = serializedObject.FindProperty("m_Script");
        _scriptName = serializedObject.FindProperty("m_ScrpitName");

        var scriptHelper = target as ScriptHelper;
        if (scriptHelper != null)
        {
            var scriptName = scriptHelper.ScriptName;
            if (string.IsNullOrEmpty(scriptName))
            {
                scriptName = scriptHelper.gameObject.name;
            }

            // 根据 GameObject 的路径或名称确定生成路径
            // 使用与 UIVariableGenerator 相同的路径生成逻辑
            var prefabPath = PrefabStageUtility.GetPrefabStage(scriptHelper.gameObject)?.assetPath;
            string outputDirectory;
            
            if (!string.IsNullOrEmpty(prefabPath))
            {
                // 使用 UIVariableGenerator 的路径生成逻辑
                var normalizedPath = prefabPath.Replace("\\", "/");
                const string PREFABBASE = "Prefabs/UIForms/";
                const string PREFABBASE_ALT = "Prefabs/";
                
                var pIndex = normalizedPath.IndexOf(PREFABBASE);
                if (pIndex >= 0)
                {
                    pIndex += PREFABBASE.Length;
                    int lastSlashIndex = normalizedPath.LastIndexOf('/');
                    var fixedPath = normalizedPath.Substring(0, lastSlashIndex + 1);
                    var subPath = fixedPath.Substring(pIndex, fixedPath.Length - pIndex);
                    outputDirectory = Path.Combine(GeneratorConfig.UIFormDirectory, subPath).Replace('\\', '/');
                }
                else
                {
                    pIndex = normalizedPath.IndexOf(PREFABBASE_ALT);
                    if (pIndex >= 0)
                    {
                        pIndex += PREFABBASE_ALT.Length;
                        int lastSlashIndex = normalizedPath.LastIndexOf('/');
                        if (lastSlashIndex > pIndex)
                        {
                            var subPath = normalizedPath.Substring(pIndex, lastSlashIndex - pIndex + 1);
                            if (subPath.StartsWith("UI/"))
                            {
                                subPath = subPath.Substring(3);
                            }
                            outputDirectory = Path.Combine(GeneratorConfig.UIFormDirectory, subPath.TrimEnd('/')).Replace('\\', '/');
                        }
                        else
                        {
                            string prefabName = Path.GetFileNameWithoutExtension(normalizedPath);
                            outputDirectory = Path.Combine(GeneratorConfig.UIFormDirectory, prefabName).Replace('\\', '/');
                        }
                    }
                    else
                    {
                        string prefabName = Path.GetFileNameWithoutExtension(normalizedPath);
                        outputDirectory = Path.Combine(GeneratorConfig.UIFormDirectory, prefabName).Replace('\\', '/');
                    }
                }
            }
            else
            {
                // 如果不是预制体，使用默认路径
                outputDirectory = Path.Combine(GeneratorConfig.UIFormDirectory, scriptName).Replace('\\', '/');
            }

            _folder = outputDirectory;
            _mainPath = Path.Combine(_folder, $"{scriptName}.cs").Replace('\\', '/').Replace("\\\\", "/");
            _variablePath = GeneratorConfig.UIVariableDirectory + $"{scriptName}.Variable.cs";
        }
    }

    protected virtual void OnDisable()
    {
        Tools.hidden = false;
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.PropertyField(_script);
            EditorGUI.EndDisabledGroup();

            EditorGUILayout.PropertyField(_scriptName, new GUIContent("Script Name", "脚本名称"));

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }

        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            // 显示 UIVariableHelper 的 Variables
            var scriptHelper = target as ScriptHelper;
            if (scriptHelper != null)
            {
                var go = scriptHelper.gameObject;
                var variableHelper = go.GetComponent<UIVariableHelper>();
                if (variableHelper == null)
                {
                    EditorGUILayout.HelpBox("UIVariableHelper 组件未找到，将在生成脚本时自动添加", MessageType.Info);
                    if (GUILayout.Button("手动添加 UIVariableHelper"))
                    {
                        variableHelper = go.AddComponent<UIVariableHelper>();
                        EditorUtility.SetDirty(go);
                    }
                }
                else
                {
                    EditorGUI.BeginDisabledGroup(true);
                    var helperSerializedObject = new SerializedObject(variableHelper);
                    var helperVariables = helperSerializedObject.FindProperty("m_Variables");
                    EditorGUILayout.PropertyField(helperVariables, new GUIContent("Variables"));
                    helperSerializedObject.ApplyModifiedProperties();
                    EditorGUI.EndDisabledGroup();
                }
            }

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }

        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            // Main script area
            EditorGUILayout.BeginHorizontal();
            var mainObj = AssetDatabase.LoadAssetAtPath<Object>(_mainPath);
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.LabelField("Script", GUILayout.Width(100));
            EditorGUILayout.ObjectField(mainObj, typeof(Object), true);
            EditorGUI.EndDisabledGroup();
            GUILayout.Space(10);
            EditorGUILayout.Separator();
            EditorGUI.BeginDisabledGroup(!mainObj);
            if (GUILayout.Button("Open", GUILayout.Width(50)))
                AssetDatabase.OpenAsset(mainObj);
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.EndHorizontal();

            // Variable area
            EditorGUILayout.BeginHorizontal();
            var variableObj = AssetDatabase.LoadAssetAtPath<Object>(_variablePath);
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.LabelField("Variable", GUILayout.Width(100));
            EditorGUILayout.ObjectField(variableObj, typeof(Object), true);
            EditorGUI.EndDisabledGroup();
            GUILayout.Space(10);
            EditorGUILayout.Separator();
            EditorGUI.BeginDisabledGroup(!variableObj);
            if (GUILayout.Button("Open", GUILayout.Width(50)))
                AssetDatabase.OpenAsset(variableObj);
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }

        EditorGUILayout.BeginVertical("HelpBox");
        {
            EditorGUI.indentLevel++;

            DrawGenerateBtn();

            EditorGUI.indentLevel--;
            EditorGUILayout.EndVertical();
        }
        serializedObject.ApplyModifiedProperties();
    }

    void DrawGenerateBtn()
    {
        GUIStyle style = new GUIStyle("Button")
        {
            alignment = TextAnchor.MiddleCenter,
            fontStyle = FontStyle.BoldAndItalic,
            fontSize = 15,
        };
        GUI.color = Color.green;
        if (GUILayout.Button("Generate", style, GUILayout.Height(25)))
        {
            GenerateScripts(serializedObject.targetObject);
        }
        GUI.color = Color.white;
    }

    void GenerateScripts(Object target)
    {
        var go = GetGameObject(target);
        if (go)
        {
            // 确保有 UIVariableHelper 组件
            var variableHelper = go.GetComponent<UIVariableHelper>();
            if (variableHelper == null)
            {
                variableHelper = go.AddComponent<UIVariableHelper>();
                EditorUtility.SetDirty(go);
            }

            try
            {
                // 使用 UIVariableGenerator 生成脚本（统一使用新的生成方式）
                var menuCommand = new MenuCommand(go);
                UIVariableGenerator.GenerateVariableScript(menuCommand);
                
                EditorUtility.SetDirty(go);
                var stage = PrefabStageUtility.GetCurrentPrefabStage();
                if (stage)
                {
                    PrefabUtility.SaveAsPrefabAsset(stage.prefabContentsRoot, stage.assetPath);
                    stage.ClearDirtiness();
                }

                Debug.Log($"{go.name} - 脚本生成成功（使用 UIVariableGenerator）");

            }
            catch (System.Exception e)
            {
                EditorUtility.DisplayDialog("错误", $"生成脚本失败: {e.Message}", "确定");
                Debug.LogError($"生成脚本失败: {e.Message}\n{e.StackTrace}");
            }
        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

    GameObject GetGameObject(Object target)
    {
        GameObject targetGameObject;
        if (target is Component component)
        {
            targetGameObject = component.gameObject;
        }
        else if (target is GameObject gameObject)
        {
            targetGameObject = gameObject;
        }
        else
        {
            targetGameObject = null;
        }
        return targetGameObject;
    }
}

